package com.qding.park.common.utils.rchl;



import java.security.Key;

import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RchlGenkey {
	public static String genDESedeKeyByBase64(int keysize, boolean printFlag)
			throws Exception {
		try {
			KeyGenerator kg = KeyGenerator.getInstance("DESede");
			kg.init(keysize);

			Key k = kg.generateKey();
			byte[] kb = k.getEncoded();

			if (printFlag) {
				System.out.print("\nkey={");
				for (int i = 0; i < kb.length - 1; i++) {
					System.out.print(kb[i] + ",");
				}
				System.out.print(kb[(kb.length - 1)]);
				System.out.print("}\n\n");
			}

			BASE64Encoder enc = new BASE64Encoder();
			return enc.encode(kb);
		} catch (Exception e) {
			throw new Exception(e.toString());
		}
	}

	public static void printBase64(String s) throws Exception {
		try {
			BASE64Decoder dec = new BASE64Decoder();
			byte[] kb = dec.decodeBuffer(s);

			System.out.print("\nkey={");
			for (int i = 0; i < kb.length - 1; i++) {
				System.out.print(kb[i] + ",");
			}
			System.out.print(kb[(kb.length - 1)]);
			System.out.print("}\n\n");

			prt("key=" + s);
		} catch (Exception e) {
			throw new Exception(e.toString());
		}
	}

	public static void prt(String s) {
		System.out.println(s);
	}

	public static void main(String[] args) {
		prt("main start...");

		String cmd = "";
		String para = "";
		try {
			if (args.length > 0)
				cmd = args[0];

			if (args.length > 1) {
				printBase64(para);
				return;
			}

			boolean printFlag = false;
			if (cmd.equals("print"))
				printFlag = true;

			String k = genDESedeKeyByBase64(168, printFlag);
			prt("key=" + k);
		} catch (Exception e) {
			e.printStackTrace();
		}

		prt("main stop.");
	}
}
